//
//  HWWuKongViewController.swift
//  HWanGame
//
//  Created by Apple on 2024/8/5.
//  Copyright © 2024 94Wan. All rights reserved.
//

import UIKit
import JXSegmentedView
import ZLPhotoBrowser
import Kingfisher
private let headerID    = "HWWuKongTopCateView"

class HWWuKongViewController: HWBaseViewController {

    var httpManager = HWHomeHttpManager()
    let circleHttpManager = HWGameCircleHttpManager()
    let gameHttpManager = HWGameDetailHttpManager()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(HWWuKongInfoCell.self,HWDynamicListCell.self,HWCommitCell.self)
        tableView.register(HWWuKongCateView.self, forHeaderFooterViewReuseIdentifier: headerID)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 306*widthScale
        return tableView
    }()
    var releaseButton:UIButton!

    var gid = ""
    private var type = 999
    private var pageIndex = 1
    private var topView = HWHomeInfoTopView()
    private var dataModel: HWWuKongHotChatModel?
    private var commitData = [HWGameDetailCommentListModel]()
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        releaseButton.isHidden = false
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        releaseButton.isHidden = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = "#F7F8FA".toColor
        
        view.addSubview(tableView)
                
        loadData()
        addRefresh()
        
        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }

        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        topView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: 170*widthScale)
        tableView.tableHeaderView = topView
        
        releaseButton = UIButton(type: .custom)
        releaseButton.setImage(UIImage(named: "Push"), for: .normal)
        releaseButton.addTarget(self, action: #selector(releaseButtonClick(_:)), for: .touchUpInside)
        currentWindow?.rootViewController?.view.addSubview(releaseButton)
        let panGesture = UIPanGestureRecognizer(target: self, action:#selector(dragAction(gesture:)))
        releaseButton.addGestureRecognizer(panGesture)
        
        releaseButton.snp.makeConstraints { make in
            make.right.equalTo(0)
            make.width.equalTo(88*widthScale)
            make.height.equalTo(88*widthScale)
            make.bottom.equalTo(-CGFloat.tabBar_height)
        }
    }
    
}

//MARK: - Data
extension HWWuKongViewController {
    
    private func loadData(){
        
        if type == 1 {
            
            self.gameHttpManager.getGameDetailCommentList(gameId: "584", pageIndex) { models in
                
                self.commitData = models
                self.tableView.reloadData()
            } failure: { errorString in
                self.tableView.mj_header?.endRefreshing()
                self.tableView.mj_footer?.endRefreshing()
            }
        }else{
            httpManager.getHomeWuKong(page: pageIndex)  { model in
                self.tableView.mj_header?.endRefreshing()
                self.tableView.mj_footer?.endRefreshing()
                self.dataModel = model
                self.topView.bannarModel = model.banners
                self.tableView.reloadData()
            } failure: { error in
                self.tableView.mj_header?.endRefreshing()
                self.tableView.mj_footer?.endRefreshing()
            }
        }
    }
    
    func addRefresh() {
        
        tableView.mj_header = MJRefreshNormalHeader()
        tableView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        tableView.mj_footer = MJRefreshBackNormalFooter()
        tableView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
    }
    
    @objc func loadNewData() -> () {
        pageIndex = 1
        loadData()
    }
    
    @objc func loadMoreData() -> () {
        self.tableView.mj_footer?.endRefreshing()
        if type == 1 {
            self.gameHttpManager.getGameDetailCommentList(gameId: self.gid, pageIndex) { models in
                self.tableView.mj_footer?.endRefreshing()
                if models.count > 0 {
                    self.commitData.append(contentsOf: models)
                }
                self.tableView.reloadData()
            } failure: { errorString in
                self.tableView.mj_footer?.endRefreshing()
            }
        }else{
            self.httpManager.getHomeWuKong(page: pageIndex) { models in
                self.tableView.mj_footer?.endRefreshing()
                if let arr = models.data, arr.count > 0 {
                    self.dataModel?.data?.append(contentsOf: arr)
                }
                self.tableView.reloadData()
            } failure: { error in

                self.tableView.mj_footer?.endRefreshing()
            }
        }
    }
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension HWWuKongViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if type == 1 {
            
            return self.commitData.count
        }
        return self.dataModel?.data?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if self.type == 1 {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "HWCommitCell", for: indexPath) as! HWCommitCell
            cell.model = commitData[indexPath.row]
            return cell
        }else{
            let infoM = self.dataModel?.data?[indexPath.row]
            if infoM?.type == 0 {
                //资讯
                let cell = tableView.dequeueReusableCell(withIdentifier: "HWWuKongInfoCell", for: indexPath) as! HWWuKongInfoCell
                cell.model = self.dataModel?.data?[indexPath.row]
                cell.likeBlock = { id in
                    self.httpManager.infoLike(type: "0", id: id) { models in
                        cell.likeImageView.isSelected = !cell.likeImageView.isSelected
                    } failure: { error in
                        self.view.showHUD(title: error)
                    }
                }
                return cell
            }else {
                //动态
                let cell = tableView.dequeueReusableCell(withIdentifier: "HWDynamicListCell", for: indexPath) as! HWDynamicListCell
                cell.model = self.dataModel?.data?[indexPath.row]
                cell.zanButtonClick = { id in
                    self.circleHttpManager.setTakeALookZan(type: "0", id: id) { message in
                        self.loadData()
                    } failure: { error in
                        
                    }
                }
                cell.jumpToDetail = { mod in
                    let detailController = HWTakeALookDetailController()
                    detailController.model = mod
                    detailController.deteleBlock = {
                        self.loadNewData()
                    }
                    self.navigationController?.pushViewController(detailController, animated: true)
                }
                cell.didSelectImage = { index,images in
                    self.selectImage(index: index, images: images)
                }
                cell.didSelectVideo = { url in
                    self.selectVideo(url: url)
                }
                return cell
            }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if self.type == 1 {
            
            let sonController = HWGameCommentSonController()
            sonController.id = commitData[indexPath.row].id
            sonController.gameId = "584"
            sonController.releaseCallBack = {
                self.loadData()
            }
            self.navigationController?.pushViewController(sonController, animated: true)
            
        }else{
            let model = self.dataModel?.data?[indexPath.row]
            if model?.type == 0 {
                let infoId = model?.primary_id
                let detailVC = HWHomeInfoDetailVC()
                detailVC.infoId = infoId ?? 0
                detailVC.loadListData = {
                    self.loadNewData()
                }
                self.navigationController?.pushViewController(detailVC, animated: true)
            }else{
                let detailController = HWTakeALookDetailController()
                detailController.model = model?.data
                detailController.deteleBlock = {
                    self.loadNewData()
                }
                self.navigationController?.pushViewController(detailController, animated: true)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerID) as! HWWuKongCateView
        header.updateCateData = { cateID in
            if cateID == 3 {
                self.toLuntanListVC()
            } else if cateID == 2 {
                let communityId = self.dataModel?.shequ_id ?? ""
                self.toCommunityController(communityId: communityId)
            } else {
                self.type = cateID
                self.loadNewData()
            }
        }
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 40*widthScale
    }
}

//MARK: - Action
extension HWWuKongViewController {
    
    private func toCommunityController(communityId: String){
        
        let community = HWGameCommunityController()
        community.communityId = communityId
        community.selectIndex = 1
        self.navigationController?.pushViewController(community, animated: true)
    }
    
    private func toLuntanListVC(){
        
        if let tabBarController = self.tabBarController {            
            tabBarController.selectedIndex = 2  // 切换到第三个Tab（索引从0开始）
            DispatchQueue.main.asyncAfter(deadline: .now()+0.5) {
                NotificationCenter.default.post(name: .toLuntanListVC, object: nil)
            }
        }
    }
    
    private func selectImage(index: Int, images: [String]) {
        
        var datas: [Any] = []
        for a in images {
            datas.append(URL(string: a)!)
        }
        let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .image
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func selectVideo(url: String) {
        
        let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .video
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    
    @objc private func releaseButtonClick(_:UIButton) -> Void {
        if HWLocallyStoredData.getLoginUserID().count>0{
            if type == 1 {
                let commentRelease = HWGameCommentReleaseController()
                commentRelease.gameId = "584"
                commentRelease.releaseCallBack = {
                    self.loadData()
                }
                self.navigationController?.pushViewController(commentRelease, animated: true)
            }else {
                
                let releaseController = HWTakeALookReleaseController()
                releaseController.gid = gid
                releaseController.releaseCallBack = {
                    self.loadData()
                }
                self.navigationController?.pushViewController(releaseController, animated: true)
            }
            
        }else{
            let loginController = HWLoginController()
            self.navigationController?.pushViewController(loginController, animated: true)
        }
        
    }
    
    @objc private func dragAction(gesture: UIPanGestureRecognizer) {
        
        // 移动状态
        let moveState = gesture.state
        switch moveState {
        case .began:
            break
        case .changed:
            // floatBtn 获取移动轨迹
            let point = gesture.translation(in: self.view)
            self.releaseButton.center = CGPoint(x: self.releaseButton.center.x + point.x, y: self.releaseButton.center.y + point.y)
            break
        case .ended:
            // floatBtn 移动结束吸边
            let point = gesture.translation(in: self.view)
            var newPoint = CGPoint(x: self.releaseButton.center.x +  point.x, y: self.releaseButton.center.y + point.y)
            if newPoint.x < screenWidth / 2.0 {
                newPoint.x = self.releaseButton.bounds.width/2 + 17*widthScale
            } else {
                newPoint.x = screenWidth - self.releaseButton.bounds.width/2 - 17*widthScale
            }
            if newPoint.y <= self.releaseButton.bounds.height/2 + 17*widthScale + navigationView.bounds.height{
                newPoint.y = self.releaseButton.bounds.height/2 + 17*widthScale + navigationView.bounds.height
            } else if newPoint.y >= self.view.bounds.height - self.releaseButton.bounds.height/2 - 17*widthScale {
                newPoint.y = self.view.bounds.height - self.releaseButton.bounds.height/2 - 17*widthScale
            }
            // 0.5秒 吸边动画
            UIView.animate(withDuration: 0.5) {
                self.releaseButton.center = newPoint
            }
            break
        default:
            break
        }
        // 重置 panGesture
        gesture.setTranslation(.zero, in: self.view)
    }
}

extension HWWuKongViewController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
